import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

print("------------ GCD ------------")
let queue = DispatchQueue(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)

// queue.sync {
//     sleep(1)
//     print("In queue sync")
// }

// queue.async {
//     sleep(1)
//     print("In queue sync")
// }

queue.asyncAfter(deadline: .now() + 1) {
    print("asyncAfter")
}

print("after invokle queue method")

/**
print("------------ DispatchGroup-wait ------------")
let workingGroup = DispatchGroup()
let workingQueue = DispatchQueue(label: "request_queue")
let timeFormatter = DateFormatter()
//日期显示格式，可按自己需求显示
timeFormatter.dateFormat = "yyy-MM-dd' at 'HH:mm:ss"
var date = Date()
var strNowTime = timeFormatter.string(from: date) as String

workingGroup.enter()
workingQueue.async {
    print("进入接口 A")
    Thread.sleep(forTimeInterval: 3)
    date = Date()
    strNowTime = timeFormatter.string(from: date) as String
    print("\(strNowTime) --- 接口 A 数据返回结果")
    workingGroup.leave()
}

workingGroup.enter()
workingQueue.async {
    print("进入接口 B")
    Thread.sleep(forTimeInterval: 5)
    date = Date()
    strNowTime = timeFormatter.string(from: date) as String
    print("\(strNowTime) --- 接口 B 数据返回结果1")
    workingGroup.leave()
}

date = Date()
strNowTime = timeFormatter.string(from: date) as String
print()
print("\(strNowTime) --- DispatchGroup-wait")
workingGroup.wait()
print("接口 A/B 都已返回结果")
 */

print("------------ DispatchGroup-notify ------------")
let workingGroup = DispatchGroup()
// 串行队列
// let workingQueue = DispatchQueue(label: "request_queue")
// 并行队列
let workingQueue = DispatchQueue(label: "myQueue", qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, target: nil)
let timeFormatter = DateFormatter()
//日期显示格式，可按自己需求显示
timeFormatter.dateFormat = "yyy-MM-dd' at 'HH:mm:ss"
var date = Date()
var strNowTime = timeFormatter.string(from: date) as String

workingGroup.enter()
workingQueue.async {
    print("进入接口 A")
    Thread.sleep(forTimeInterval: 3)
    date = Date()
    strNowTime = timeFormatter.string(from: date) as String
    print("\(strNowTime) --- 接口 A 数据返回结果")
    workingGroup.leave()
}

workingGroup.enter()
workingQueue.async {
    print("进入接口 B")
    Thread.sleep(forTimeInterval: 5)
    date = Date()
    strNowTime = timeFormatter.string(from: date) as String
    print("\(strNowTime) --- 接口 B 数据返回结果1")
    workingGroup.leave()
}

date = Date()
strNowTime = timeFormatter.string(from: date) as String
print("\(strNowTime) --- DispatchGroup-wait")
workingGroup.notify(queue: workingQueue) {
    date = Date()
    strNowTime = timeFormatter.string(from: date)
    print("\(strNowTime) --- 接口 A/B 都已返回结果")
}

print("不阻塞进程, 继续往下执行")

